var Organization = function () {

    var basePath = ROOT_PATH + 'upms/organization/',
        pagePath = ROOT_PATH + 'pages/upms/organization/',
        $orgzTree = null,
        currNode = null,//当前选中的节点
        $form = null;

    /**
     * 初始化树形网格id
     * @param treeId
     */
    function initTreeGrid(treeId) {
        $orgzTree = BsGridUtil.initBsTreeGrid({
            url: basePath + "list",
            gridId: treeId,
            treeColumn: 1,//伸缩图标显示在哪行
            toolbar:"#orgTb",
            columns: [
                {checkbox: true},
                {field: 'id', title: 'id', visible: false},
                {field: 'name', title: "名称"},
                {field: 'remark', title: "描述"},
                {
                    field: 'opt', title: "操作",
                    formatter: function (val, row, index) {
                        if (row.seq != 1) {
                            return "<a href='javascript:Organization.edit(" + row.id + ")' class='btn btn-xs btn-primary'><span class='glyphicon glyphicon-pencil'>编辑</a>"
                        }
                    }
                }
            ],
        });
        return $orgzTree;
    }

    /**
     * 初始化只读树
     */
    function initReadOnlyTree(gridId,opt) {
        var op = {
            url: basePath + "list",
            gridId: gridId,
            toolbar:"",
            showRefresh:false,
            treeColumn: 1,//伸缩图标显示在哪行
            columns: [
                {checkbox: true,formatter:function (val,row) {
                        if (row.lvl == 1){
                            return{
                                disabled:true
                            }
                        }
                    }},
                {field: 'id', title: 'id', visible: false},
                {field: 'name', title: "名称"},
                {field: 'desc', title: "描述"},
            ],
        };
        op = $.extend(true,opt,op);
        return BsGridUtil.initBsTreeGrid(op);
    }

    function initTree(treeId) {
        /**
         * 点击事件
         */
        clickDom = function (event, treeId, treeNode) {

        }

        /**
         * 加载完成事件
         * @param event
         * @param treeId
         * @param treeNode
         */
        zTreeOnAsyncSuccess = function (event, treeId, treeNode) {
            
        }

        var setting = {
            treeId: treeId,
            async: {
                url: basePath + "listOrgAndDept"
            },
            check: {
                enable: false,
            },
            callback:{
                onClick:clickDom,
                onAsyncSuccess: zTreeOnAsyncSuccess,
            }
        };
        return Tree.getTree(setting);
    }

    /**
     * 初始化省市区选择框
     * @param form
     */
    function initArea(form, lvl) {
        var $form = $(form);
        var AreaPickerOptions = {
            remote: {
                url: ROOT_PATH + "common/area/findLinkagePickerData"
            },
            placeholder: '请选择省/市',
            lvlOne: { //第一级
                id: '', //默认id
                formItemName: 'provinceId',
                idField: 'id', //默认使用的id字段
                textField: 'provinceName', //默认使用的显示字段
                tabText: '省份',//标签页显示名称
                onSelect: function (row) {
                    var text = row.text;
                    $form.find("input[name='name']").val();
                    $form.find("input[name='name']").val(text);
                }

            },
            lvlTwo: {
                id: '',
                formItemName: 'cityId',
                idField: 'id',
                textField: 'cityName',
                tabText: '城市',
                onSelect: function (row) {
                    var text = row.text;
                    $form.find("input[name='name']").val(text);
                }
            },
            lvlThree: {
                id: '',
                formItemName: 'countyId',
                idField: 'id',
                textField: 'countyName',
                tabText: '区县',
                onSelect: function (row) {
                    var text = row.text;
                    $form.find("input[name='name']").val(text);
                }
            }
        };
        if (lvl == 1) {
            AreaPickerOptions = {
                remote: {
                    url: ROOT_PATH + "common/area/findLinkagePickerData"
                },
                placeholder: '请选择省/市',
                lvlOne: { //第一级
                    id: '', //默认id
                    formItemName: 'provinceId',
                    idField: 'id', //默认使用的id字段
                    textField: 'provinceName', //默认使用的显示字段
                    tabText: '省份',//标签页显示名称
                    onSelect: function (row) {
                        var text = row.text;
                        $form.find('input[name="name"]').val(text);
                    }
                },
                level: 'lvlOne' //仅显示到1级

            };
        }
        $form.find('#cityPicker').linkagePicker(AreaPickerOptions);

    }

    /**
     * 创建组织机构
     * @param id
     * @param treeNode
     */
    function create() {
        var selected = getSelected();
        if (selected && selected.length > 0) {
            var currNode = selected[0];
            $.Get(basePath + "create", {id: currNode.id}, function (page) {
                var $dialog = $(page);
                var $form = $dialog.find("form:first");
                $dialog.modal().on('shown.bs.modal', function (e) {
                    $.Get(basePath + "get", {id: currNode.id}, function (data) {
                        $form.find('input[name="pid"]').val(data.data.id);
                        $form.find('input[name="name"]').focus();
                        // $form.find('input[name="provinceId"]').val(data.data.provinceId);
                        // $form.find('input[name="cityId"]').val(data.data.cityId);
                        // $form.find('input[name="countyId"]').val(data.data.countyId);
                        initFormValidation($form, $dialog);
                    })
                });
            })
        } else {
            Dialog.warning("请选中节点")
        }
    }

    /**
     * 修改机构
     */
    function edit(id) {
        $.Get(basePath + "edit", function (page) {
            var $dialog = $(page);
            var $form = $dialog.find("form:first");
            $dialog.modal().on('shown.bs.modal', function (e) {
                $.Get(basePath + "get", {id: id}, function (data) {
                    FormUtils.setValues($form, data.data);
                    // initArea($form, data.data.lvl);
                    initFormValidation($form, $dialog);
                })
            });
        })
    }

    /**
     * 获取当前选中行
     */
    function getSelected() {
        return $orgzTree.bootstrapTable("getSelections");
    }

    /**
     * 刷新当前表格
     */
    function refresh() {
        $orgzTree.bootstrapTable("refresh");
    }

    /**
     * 给表单加上验证
     * @param formId
     */
    function initFormValidation(formId, $dialog) {
        $form = $(formId);
        FormUtils.validate($form, {
            rules:{
                name: {
                    maxlength: 10,
                    required: true
                },
                remark:{
                    maxlength: 100,
                }
            },
            message:{
                name: {
                    required: "请输入机构名称",
                    maxlength: "最多允许输入10个字符"
                },
                remark:{
                    maxlength: "最多只允许输入100个字符"
                }
            },
            submitHandler: function () {
                var data = FormUtils.getFormObj($form);
                var url = basePath;
                if (data.id) {
                    url += "/edit";
                } else {
                    url += "/create";
                }
                $.Ajax({
                    url: url,
                    data: data,
                    method: "post",
                    container: $form,
                    success: function (result) {
                        $dialog.modal('hide');
                        $orgzTree.bootstrapTable("refresh");
                    }
                });
            }
        })
    }

    /**
     * 删除节点
     */
    function del() {
        var selected = getSelected();
        if (selected && selected.length > 0) {
            var currentNode = selected[0];
            $.Post(basePath + "delete", {id: currentNode.id}, function (data) {
                if (data.success) {
                    Dialog.success(data.data);
                    refresh();
                } else {
                    Dialog.danger(data.data)
                }
            })
        }
    }

    return {
        initTreeGrid:initTreeGrid,
        initTree: initTree,
        create: create,
        edit: edit,
        initFormValidation: initFormValidation,
        del: del,
        initReadOnlyTree: initReadOnlyTree
    }
}();